<template>
  <view class="supplier-container">
    <!-- 新增按钮 -->
    <view class="action-bar">
      <button @click="showAddSupplierModal" class="action-button">新增供应商</button>
    </view>

    <!-- 搜索框 -->
    <view class="search-bar">
      <input type="text" v-model="searchQuery" placeholder="输入名称以搜索供应商" class="search-input" />
      <button @click="searchSuppliers" class="search-button">搜索</button>
    </view>

    <!-- 供应商列表 -->
    <view class="supplier-list">
      <!-- 空空如也提示 -->
      <view v-if="suppliers.length === 0" style='display: flex;align-items: center;justify-content: center;margin-top: 50px;'>
        <image src='../../Resources/Image/空空如也.png' style='width: 120px;height:120px;'></image>
      </view>
      <view v-for="(supplier, index) in suppliers" :key="index" class="supplier-item" style="height: 50px;">
        <view class="supplier-info">
          <view class="supplier-name">{{ supplier.supplier_no }}</view>
          <view class="supplier-code">{{ supplier.supplier_name }}</view>
        </view>
        <view class="supplier-actions">
			<image src='../../Resources/Image/详细信息.png' style='width: 22px;height:22px;margin-right: 5px;' @click="showInfo(supplier)"></image>
          <image src='../../Resources/Image/编辑.png' style='width: 25px;height:25px;margin-right: 5px;' @click="editSupplier(supplier)"></image>
          <image src='../../Resources/Image/删除.png' style='width: 27px;height:27px;' @click="deleteSupplier(supplier)"></image>
		  
        </view>
      </view>
    </view>

    <!-- 新增供应商弹窗 -->
    <view v-if="showModal" class="modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">新建供应商</text>
        </view>
        <view class="modal-body">
          <input type="text" v-model="newSupplier.supplier_no" placeholder="供应商代号" class="input-field" />
          <input type="text" v-model="newSupplier.supplier_name" placeholder="供应商名称" class="input-field" />
          <input type="text" v-model="newSupplier.supplier_phone" placeholder="供应商电话" class="input-field" />
          <input type="text" v-model="newSupplier.supplier_address" placeholder="供应商地址" class="input-field" />
          <input type="text" v-model="newSupplier.supplier_contact" placeholder="供应商联系人" class="input-field" />
          <picker mode="selector" :range="['请选择合作状态','合作中', '暂停合作', '终止合作']" @change="onCooperationStatusChange" :value="0">
            <view class="picker">{{ newSupplier.supplier_status }}</view>
          </picker>
          <input type="number" v-model="newSupplier.order_num" placeholder="排序权重" class="input-field" />
          <textarea v-model="newSupplier.remark" placeholder="备注" class="textarea-field"></textarea>
        </view>
        <view class="modal-footer">
          <button @click="submitSupplier" class="action-button">提交</button>
          <button @click="hideModal" class="action-button">取消</button>
        </view>
      </view>
    </view>
	
	
	<!-- 修改供应商 -->
	<view v-if="AlterShowModal" class="modal">
	  <view class="modal-content">
	    <view class="modal-header">
	      <text class="modal-title">新建供应商</text>
	    </view>
	    <view class="modal-body">
	      <input type="text" v-model="newSupplier.supplier_no" placeholder="供应商代号" class="input-field" />
	      <input type="text" v-model="newSupplier.supplier_name" placeholder="供应商名称" class="input-field" />
	      <input type="text" v-model="newSupplier.supplier_phone" placeholder="供应商电话" class="input-field" />
	      <input type="text" v-model="newSupplier.supplier_address" placeholder="供应商地址" class="input-field" />
	      <input type="text" v-model="newSupplier.supplier_contact" placeholder="供应商联系人" class="input-field" />
	      <picker mode="selector" :range="['请选择合作状态','合作中', '暂停合作', '终止合作']" @change="onCooperationStatusChange">
	        <view class="picker">{{ newSupplier.supplier_status }}</view>
	      </picker>
	      <input type="number" v-model="newSupplier.order_num" placeholder="排序权重" class="input-field" />
	      <textarea v-model="newSupplier.remark" placeholder="备注" class="textarea-field"></textarea>
	    </view>
	    <view class="modal-footer">
	      <button @click="alertSupplier" class="action-button">提交</button>
	      <button @click="hideModal" class="action-button">取消</button>
	    </view>
	  </view>
	</view>
	
	<!-- 显示详细信息 -->
	<view v-if="ShowModalInfo" class="modal">
	  <view class="modal-content">
	    <view class="modal-header">
	      <text class="modal-title">供应商详细信息</text>
	    </view>
	    <view class="modal-body">
	      <input type="text" v-model="newSupplier.supplier_no" placeholder="供应商代号" class="input-field" :disabled="true" />
	      <input type="text" v-model="newSupplier.supplier_name" placeholder="供应商名称" class="input-field"  :disabled="true"/>
	      <input type="text" v-model="newSupplier.supplier_phone" placeholder="供应商电话" class="input-field"  :disabled="true" />
	      <input type="text" v-model="newSupplier.supplier_address" placeholder="供应商地址" class="input-field"  :disabled="true" />
	      <input type="text" v-model="newSupplier.supplier_contact" placeholder="供应商联系人" class="input-field" :disabled="true"/>
	      <picker mode="selector" :range="['请选择合作状态','合作中', '暂停合作', '终止合作']" @change="onCooperationStatusChange" :disabled="true">
	        <view class="picker">{{ newSupplier.supplier_status }}</view>
	      </picker>
	      <input type="number" v-model="newSupplier.order_num" placeholder="排序权重" class="input-field" :disabled="true" />
	      <textarea v-model="newSupplier.remark" placeholder="备注" class="textarea-field" :disabled="true"></textarea>
	    </view>
	    <view class="modal-footer">
	      <button @click="hideModal" class="action-button">返回</button>
	    </view>
	  </view>
	</view>
	
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { config } from '../../config';
import { TokenStore } from '../../Store/TokenStore';
import { LoginState } from '../../util/LoginSate';
import { onPullDownRefresh , onReachBottom } from "@dcloudio/uni-app"

const selectedStatus = ['请选择合作状态','合作中', '暂停合作', '终止合作']

//修改供应商的弹窗
let AlterShowModal = ref(false);

//显示详细信息的弹窗
let ShowModalInfo  =ref(false);

// 供应商数据 根据搜索状态变化啊而变化
let suppliers = ref([
	
]);

// 全部供应商数据 不随任何变化
let AllSuppliers = ref([])

//显示供应商信息
function showInfo(supplier){
	newSupplier.value = {...supplier};
	//newSupplier.value.supplier_status = selectedStatus[newSupplier.value.supplier_status]
	ShowModalInfo.value = true;
}

//分页信息
let PageInfo = ref({
		size:10,
		page:1
	})

onMounted(()=>{
	if(!LoginState()){
		uni.showToast({
		  title: '登录失效',
		  icon: 'error'
		});
		uni.redirectTo({
			url:"/pages/index/index"
		})
		return ;
	}
	AllSupplier()
})

//--------------------------------------------------------------分页查询部分---------------------------------------------------------

//分页获取所有供应商
function AllSupplier(){
	uni.request({
		url:`${config.baseURL}/Supplier/AllSuppliers`,
		method:'POST',
		data:PageInfo.value,
		header: {
			'content-type': 'application/json' // 设置请求头为 JSON
		},
		success:(res)=>{
			console.log(res.data.data);
			if(res.data.data === "error"){
				uni.showToast({
				  title: "数据库错误",
				  icon: 'error'
				});
			}
			else{
				let data = JSON.parse(res.data.data);
				suppliers.value.push(...data)
				AllSuppliers.value.push(...data)
				PageInfo.value.page+=PageInfo.value.size;//更新页码
			}
		}
	})
}

onReachBottom(()=>{
	console.log("进入追加数据逻辑")
	AllSupplier()
})

//------------------------------------------------------------------------------------------------------------


//---------------------------------------------下拉刷新部分-----------------------------------------------------


onPullDownRefresh(()=>{
	console.log("进入下拉刷新逻辑")
	
	AllSuppliers.value = [];
	
	suppliers.value = [];
	
	PageInfo.value.page = 1;
	
	AllSupplier()
	
	uni.stopPullDownRefresh()
})


//------------------------------------------------------------------------------------------------------------




// 新增供应商弹窗状态
const showModal = ref(false);
const newSupplier = ref({ 
	id:'',
	supplier_no:'',
	supplier_name:'',
	supplier_phone:'',
	supplier_address:'',
	supplier_contact:'',
	supplier_status:'请选择合作状态',
	order_num:'',
	remark:''
});

// 搜索框数据
const searchQuery = ref('');

// 显示新增供应商弹窗
const showAddSupplierModal = () => {
  showModal.value = true;
};

// 隐藏新增供应商弹窗
const hideModal = () => {
  showModal.value = false;
  AlterShowModal.value = false;
  ShowModalInfo.value = false;
  Object.keys(newSupplier.value).forEach(key => {
    newSupplier.value[key] = '';
  });
  newSupplier.value.supplier_status = '请选择合作状态'
  AllSupplier()
};

// 提交新增供应商
const submitSupplier = () => {
	newSupplier.value.id = 1;
	console.log("当前数据："+JSON.stringify(newSupplier.value))
  if (Object.values(newSupplier.value).some(value => value === '')) {
    uni.showToast({
      title: "请填写所有字段",
      icon: 'error'
    });
	return ;
  }
  uni.request({
  	url:`${config.baseURL}/Supplier/AddSupplier`,
	method:'POST',
	data:newSupplier.value,
	header: {
		'content-type': 'application/json', // 设置请求头为 JSON
		'Authorization': TokenStore().token
	},
	success:(res)=>{
		console.log(res.data.data);
		if(res.data.data === "error"){
			uni.showToast({
			  title: "数据库错误",
			  icon: 'error'
			});
		}
		else if(res.data.data === "1"){
			uni.showToast({
			  title: "添加成功,请下拉刷新后查看",
			  icon: 'none'
			});
			Object.keys(newSupplier.value).forEach(key => {
			  newSupplier.value[key] = '';
			});
			newSupplier.value.supplier_status = '请选择合作状态'
			hideModal();
		}
		else if(res.data.data === "0"){
			uni.showToast({
			  title: "服务器繁忙",
			  icon: 'error'
			});
		}
		else if(res.data.data === "令牌过期"){
			uni.showToast({
			  title: "请重新登录",
			  icon: 'error'
			});
		}
	},
	fail:(err)=>{
		uni.showToast({
		  title: err.errMsg,
		  icon: 'error'
		});
	}
  })
};

// 编辑供应商
const editSupplier = (supplier) => {
  // 这里可以弹出编辑框，或者跳转到编辑页面
  console.log('编辑供应商', supplier);
  newSupplier.value = {...supplier};
  //newSupplier.value.supplier_status = selectedStatus[newSupplier.value.supplier_status]
  console.log("数据迁移成功！"+JSON.stringify(newSupplier.value));
  AlterShowModal.value = true;
};

//提交编辑业务
function alertSupplier(){
	uni.request({
		url:`${config.baseURL}/Supplier/AlterSupplier`,
		method:'POST',
		data:newSupplier.value,
		header: {
			'content-type': 'application/json', // 设置请求头为 JSON
			'Authorization': TokenStore().token
		},
		success:(res)=>{
			console.log(res.data.data);
			if(res.data.data === '1'){
				uni.showToast({
				  title: "修改成功",
				  icon: 'success'
				});
				AllSuppliers.value = [];
				
				suppliers.value = [];
				
				PageInfo.value.page = 1;
				
				AllSupplier()
				Object.keys(newSupplier.value).forEach(key => {
				  newSupplier.value[key] = '';
				});
				newSupplier.value.supplier_status = '请选择合作状态'
				AlterShowModal.value = false
			}
			else if(res.data.data === 'error'){
				uni.showToast({
				  title: "数据库错误",
				  icon: 'error'
				});
			}
		},
		fail:(err)=>{
			uni.showToast({
			  title: err.errMsg,
			  icon: 'error'
			});
		}
	})
}

// 删除供应商
const deleteSupplier = (supplier) => {
  newSupplier.value = supplier
  uni.request({
  	url:`${config.baseURL}/Supplier/DeleteSupplier`,
	method:'POST',
	data:newSupplier.value,
	header: {
		'content-type': 'application/json', // 设置请求头为 JSON
		'Authorization': TokenStore().token
	},
	success:(res)=>{
		if(res.data.data === '1'){
			uni.showToast({
			  title: "删除成功",
			  icon: 'success'
			});
			Object.keys(newSupplier.value).forEach(key => {
			  newSupplier.value[key] = '';
			});
			newSupplier.value.supplier_status = '请选择合作状态'
			AllSuppliers.value = [];
			
			suppliers.value = [];
			
			PageInfo.value.page = 1;
			
			AllSupplier()
		}
		else if(res.data.data === 'error'){
			uni.showToast({
			  title: "数据库错误",
			  icon: 'error'
			});
		}
	},
	fail:(err)=>{
		uni.showToast({
		  title: err.errMsg,
		  icon: 'error'
		});
	}
  })
};

// 合作状态改变事件
const onCooperationStatusChange = (e) => {
	console.log(e);
   newSupplier.value.supplier_status = selectedStatus[e.detail.value];
   console.log("状态改变"+newSupplier.value.supplier_status);
   
};

// 搜索供应商
const searchSuppliers = () => {
  // 搜索逻辑可以在这里实现，或者使用 computed 属性进行过滤
  if(searchQuery.value === ''){
	  suppliers.value = AllSuppliers.value
	  return ;
  }
  
  const searchedGoods = AllSuppliers.value.filter(item => item.supplier_name === searchQuery.value);
  console.log("查询出数据"+JSON.stringify(searchedGoods))
  suppliers.value = searchedGoods;
};
</script>

<style scoped>
.supplier-container {
  padding: 20px;
  background-color: #eef7f6; /* 浅蓝色背景 */
  height: 100vh;
}

.action-bar {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.action-button {
  border: none;
  border-radius: 5px;
  cursor: pointer;
  width: 80%;
  height: 40px;
  background-color: #3e92cc; /* 蓝色 */
  color: white;
  transition: background-color 0.3s;
}

.action-button:hover {
  background-color: #3079a4;
}

.search-bar {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.search-input {
  padding: 10px;
  width: 70%;
  border: 1px solid #eaeaea;
  border-radius: 5px;
  margin-right: 10px;
}

.search-button {
  border: none;
  border-radius: 5px;
  width: 20%;
  cursor: pointer;
  height: 40px;
  background-color: #007aff; /* 蓝色 */
  color: white;
  transition: background-color 0.3s;
}

.search-button:hover {
  background-color: #0051b3;
}

.supplier-list {
  width: 100%;
  margin: 0 auto;
}

.supplier-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.supplier-item:hover {
  transform: translateY(-5px);
}

.supplier-info {
  display: flex;
  align-items: center;
}

.supplier-name {
  margin-right: 10px;
  color: #333;
}

.supplier-code {
  color: #666;
}

.supplier-actions {
  display: flex;
  align-items: center;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.modal-header {
  font-size: 18px;
  font-weight: bold;
  color: #007aff;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.modal-body {
  margin: 20px 0;
}

.input-field, .textarea-field {
  width: 95%;
  padding: 10px;
  margin-bottom: 20px;
border: 1px solid #eaeaea;
border-radius: 5px;
height:20px;
}

.picker {
padding: 10px;
background-color: #eaeaea;
border-radius: 5px;
margin-bottom: 20px;
}

.modal-footer {
display: flex;
justify-content: flex-end;
}

.modal-footer button {
margin-left: 10px;
}
</style>